<?php
require(dirname(__FILE__)."/"."../inc/common.inc.php");
admin(8);

//生成组织树
function department_m_teee($id){
    global $db,$pre;
    $depart_info = $db->get_one("select * from {$pre}department where id='{$id}' ");

    if(!empty($depart_info)){
        $i = 0;
        global $cache_m_id;
        $cache_tree = array();
        do{
            $cache_m_id = empty($cache_m_id)?$depart_info['parentid']:$cache_m_id;
            $cache_tree[] = intval($cache_m_id);
            $type_info = $db->get_one("select * from {$pre}department where id='{$cache_m_id}' ");
            $cache_m_id = $type_info['parentid'];
            $i++;
        }while($type_info['parentid']!='0' && $i < 10 && !empty($type_info['parentid']));
        sort($cache_tree);
        $cache_str_tree = implode(',',$cache_tree);

        $db->query("update {$pre}department set m_tree='{$cache_str_tree}' where id='{$id}'");
        return 1;
    }else{
        return 0;
    }
}


//保存数据——新
if ($action == 'regit'){
    if($id){
        //修改部门
       
            $db->query("UPDATE {$pre}department SET name='".filtrate($name)."',`order`='".filtrate($order)."',parentid='$parentid' where id='$id'");

            $result = department_m_teee($id);

            $str='修改';
            logo('修改部门');
            ob_clean();
            ob_start();
            echo 'YES|修改成功';
            exit;
      
    }else{
        if($name==''){
            ob_clean();
            ob_start();
            echo 'ERROR|部门名字为空！';
            exit;
        }
        $parentid=$parentid?$parentid:0;
        $db->query("INSERT INTO {$pre}department SET name='".filtrate($name)."',`order`='".filtrate($order)."',parentid='$parentid' ");
        $nid=$db->insert_id();

        $result = department_m_teee($nid);
      
       
        $str='新增';
        logo('新增部门');
        ob_clean();
        ob_start();
        echo 'YES|添加成功';
        exit;
      
    }
    exit();
}

//保存
if (!empty($regit)){
    if($id){
        //修改部门
    
            $db->query("UPDATE {$pre}department SET name='".filtrate($name)."',`order`='".filtrate($order)."',parentid='$parentid' where id='$id'");
            $str='修改';
            logo('修改部门');
      
    }else{
        if($name==''){
            showerr('部门名字为空');
        }
        $parentid=$parentid?$parentid:0;
        $db->query("INSERT INTO {$pre}department SET name='".filtrate($name)."',`order`='".filtrate($order)."',parentid='$parentid' ");
        $nid=$db->insert_id();
     
            $str='新增';
            logo('新增部门');
     
    }
    refreshto('?',$str.'成功!',0.5);
    exit;
}

if($act=='tree'){
    $query_ob2 = $db->query("select a.parentid,a.id,a.name,a.order,(select count(*) shu from {$pre}department where  parentid=a.id ) shu,(select name from {$pre}department where  id=a.parentid ) pname from {$pre}department a where a.parentid='{$id}' order by a.order desc");
    while ($rs=$db->fetch_array($query_ob2)){
        if($rs['shu']>0){
            echo '<li class="close" id="tri_'.$rs['id'].'"><i onclick="get_tree('.$rs['id'].')"></i><a href="javascript:;" onclick="regname(\''.$rs['id'].'\',\''.$rs['name'].'\',\''.$rs['order'].'\',\''.$rs['phone'].'\',\''.$rs['parentid'].'\',\''.($rs['pname']?$rs['pname']:'顶级').'\',\''.$rs['type'].'\')">'.$rs['name'].'</a>';
            echo '<ul id="tree_'.$rs['id'].'"></ul>';
            echo '</li>';
        }else{
            echo '<li class="node"><i></i><a href="javascript:;" onclick="regname(\''.$rs['id'].'\',\''.$rs['name'].'\',\''.$rs['order'].'\',\''.$rs['phone'].'\',\''.$rs['parentid'].'\',\''.($rs['pname']?$rs['pname']:'顶级').'\',\''.$rs['type'].'\')">'.$rs['name'].'</a></li>';
        }
    }
    exit;
}

if($act=='del'){
    if($db->get_one("select * from {$pre}department a where a.parentid='{$id}'")){
        showerr('删除失败，该单部门下还有子部门');
    }
    $db->query("delete from {$pre}department where id='{$id}'  ");
    logo('删除部门');
    refreshto('?','删除成功','0.5');
 
}
?>
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <!--[if lt IE 9]>
    <script type="text/javascript" src="js/html5.js"></script>
    <script type="text/javascript" src="js/respond.min.js"></script>
    <script type="text/javascript" src="js/PIE_IE678.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="css/H-ui.css"/>
    <link type="text/css" rel="stylesheet" href="css/H-ui.admin.css"/>
    <link type="text/css" rel="stylesheet" href="font/font-awesome.min.css"/>
    <!--[if IE 7]>
    <link href="font/font-awesome-ie7.min.css" rel="stylesheet" type="text/css" />
    <![endif]-->
    <title><?=$webdb['title']?></title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
<nav class="Hui-breadcrumb"><?=get_category(8)?> <a class="btn btn-success radius r mr-20" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新" ><i class="icon-refresh"></i></a></nav>
<div class="pd-20">
    <style>
        .tree{position: absolute; left: 0; top:0;right:0; bottom: 0;}
        .tree ul{padding: 0px 0px 0px 10px; margin: 0px; clear: left}
        .tree li{padding: 0px; margin: 0px; height: 22px; line-height: 22px; list-style: none;  clear: left}
        .tree li i{background: url(images/zTreeStandard.png); width: 16px; height: 16px; float: left; margin-top: 2px; cursor: pointer}
        .tree li.open i{background-position:209px -15px;}
        .tree li.close i{background-position:209px 0px; }
        .tree li.node i{background-position:209px -30px;}
        .tree li a{float: left;text-indent:2px; color: #000000;}
        .bianjia{display: none}
        .close{opacity:1!important;}
        a{font-size: 14px; color: #000000;}
    </style>

    <table style="width: 100%" >
        <tr>
            <td width="260" style="width: 260px; position: relative; height: 400px;" valign="top" id="td_1"  >
                <div class="tree" style=" overflow: auto">
                    <ul id="tree_0"></ul>
                </div>
                <script>
                    function get_tree(id){
                        var text=$("#tree_"+id).text();
                        if(text!==""){
                            $("#tri_"+id).removeClass("close");
                            $("#tri_"+id).removeClass("open");
                            if($("#tree_"+id).css('display')==='none'){
                                $("#tree_"+id).show();
                                $("#tri_"+id).addClass("open");
                            }else{
                                $("#tree_"+id).hide();
                                $("#tri_"+id).addClass("close");
                            }
                        }else{
                            $("#tri_"+id).removeClass("close");
                            $("#tri_"+id).addClass("open");
                            $.get("?act=tree",{id:id},function(result){
                                $("#tree_"+id).append(result);
                                if(id=='0' && text==""){
                                    get_tree(1);
                                }
                            });
                        }
                    }
                    get_tree(0);
                </script>
            </td>
            <td valign="top">
                <?php
                // $bminfo=$db->get_one("select * from  {$pre}department where  parentid='0' order by `order` desc limit 0,1");
                ?>
                <form name="form1"  method="post" class="form_form">
                    <table class="formtable" style="margin-left: -1px; margin-top: -1px;" >
                        <input type="hidden" name="id" id="bm_id" value="<?=$bminfo['id']?>" />
                        <input type="hidden" name="parentid" id="bm_parentid" value="<?=$bminfo['parentid']?>" />
                        <tr>
                            <td width="200"  height="35" align="right"  class="tlabel">部门名称：</td>
                            <td  height="35"  ><input name="name" id="bm_name" type="text" value="<?=$bminfo['name']?>" size="40" class="input-text"></td>
                        </tr>
                        <tr>
                            <td width="200"  height="35" align="right"  class="tlabel">上级名称：</td>
                            <td  height="35"  ><input name="pname" id="bm_pname" type="text" value="" readonly=""   size="40" class="input-text "></td>
                        </tr>
                        <tr>
                            <td  height="35" align="right" class="tlabel">部门排序：</td>
                            <td  height="35"  ><input name="order" id="bm_order" type="text" value="<?=$bminfo['order']?>" size="40" class="input-text "></td>
                        </tr>
                      
                    </table>

                    <div class="formbtn" style="width: 100%; text-align: center;">
                        <a class="btn btn-success radius" id="sub_sub">添加</a>
                        <input type="submit" value="添加" id="bm_regit" name="regit"  class="btn btn-success radius" style="display:none;">
                        <input type="reset" value="重置" onclick=" $('#bm_regit').val('添加');$('#zb_set_id').hide();"  class="btn btn-success radius">
                        <input type="button" value="删除" onclick="shanchu()"  class="btn btn-success radius">
                       
                    </div>
                </form>
            </td>
        </tr>
    </table>

    <script type="text/javascript" src="layer/layer.min.js"></script>
    <script type="text/javascript" src="js/H-ui.js"></script>
    <script type="text/javascript" src="js/H-ui.admin.js"></script>
    <script src="layer/layer.js"></script>
    <script>
        function regname(id,name,order,phone,parentid,pname,type){
            $('#bm_id').val(id);
            $('#bm_name').val(name);
            $('#bm_order').val(order);
            //$('#bm_phone').val(phone);
            $('#bm_parentid').val(parentid);
            $('#bm_pname').val(pname);
            $('#zb_set_id').show();
            $('#bm_regit').val('保存');
            $('#sub_sub').text('保存');
            $('#select_type').val(type);
        }
        setTimeout(function(){
            $('#td_1').height($(document).height()-80);
        },500);
   
        $('#bm_pname').on('click', function(){
            layer.open({
                title:'部门选择',
                type: 2,
                area: ['400px', '450px'],
                fixed: true, //不固定
                maxmin: false,
                content: 'department_select.php'
            });
        });

        //提交信息
        $('#sub_sub').click(function(){
            $.ajax({
                url:'?action=regit',
                data:$('.form_form').serialize(),
                type:'post',
                success:function(data) {
                    var data_arr = data.split('|');
                    if(data_arr[0] == 'YES'){
                        alert(data_arr[1]);
                        return false;
                    }else if(data_arr[0] == 'ERROR'){
                        alert(data_arr[1]);
                        return false;
                    }
                }
            })
        });

        function shanchu(){
            var id= $('#bm_id').val();
            if(id===''){
                layer.alert('请选择部门')
            }else{
                layer.confirm('是否真的删除？', {
                }, function(){
                    window.location='?act=del&id='+id;
                }, function(){
                    // layer.msg('1', {icon: 1});
                });
            }
        }
    </script>
</div>
</body>
</html>